// 用户相关的路由处理
const db = require("../db/index");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const config = require("../config");
// 注册
exports.register = (req, res) => {
  const userinfo = req.body;
  // 判断数据是否合法
  // if (!userinfo.username || !userinfo.password) {
  //   return res.cc("用户名或密码不合法");
  // }
  // 用户名是否被占用
  const sql = `select * from ev_users where username=?`;
  db.query(sql, userinfo.username, (err, results) => {
    if (err) {
      // return res.send({
      //   status: 1,
      //   message: err.message,
      // });
      return res.cc(err);
    }
    if (results.length > 0) {
      return res.cc("用户名已被占用,请更换用户名");
    }

    // 注册成功
    const insertSql = "INSERT INTO ev_users SET ?";
    // 数据加密
    userinfo.password = bcrypt.hashSync(userinfo.password, 10);
    db.query(insertSql, userinfo, (err, results) => {
      if (err) return res.cc(err);
      if (results.affectedRows !== 1)
        return res.cc("注册用户失败，请稍后再试！");
      res.cc("注册成功", 0);
    });
  });
};

// 登录
exports.login = (req, res) => {
  const userinfo = req.body;
  exports.user = userinfo;
  const sql = "select * from ev_users where username=?";
  db.query(sql, userinfo.username, (err, results) => {
    if (err) return res.cc(err);
    if (results.length !== 1) return res.cc("用户不存在，请注册");
    // 判断用户密码是否匹配
    const isPasswordCorrect = bcrypt.compareSync(
      userinfo.password,
      results[0].password
    );
    if (!isPasswordCorrect) return res.cc("密码错误");
    const user = { ...results[0], password: "", user_pic: "" };
    // 生成token
    const tokenStr = jwt.sign(user, config.jwtSecretKey, {
      expiresIn: config.expiresIn,
    });
    res.send({
      status: 0,
      message: "登录成功",
      token: "Bearer " + tokenStr,
    });
    // 登录成功
    // res.cc("登录成功", 0);
  });
};
